<?php

namespace App\Services\OpenWechat;


use App\Models\OpenWechat\Authorizer;
use EasyWeChat\Kernel\Support\Collection;


/**
 * 保存素材media id 成文件
 * 或上传 material
 */
class MaterialSave
{

    private $wx_app;

    /**
     * MaterialSave constructor.
     * @param Authorizer $authorizer
     * @throws \Exception
     */
    public function __construct(Authorizer $authorizer)
    {
        $author_wx = new AppFactory;
        //        $wx_temp = (new AppFactory())->authorizerApp($appid)->material;

        $this->wx_app = $author_wx->authorizerApp($authorizer->authorizer_appid);
    }

    /**
     * 用 media id 保存成本地文件并返回文件路径
     *
     * @param $media_id
     * @param null $file_name
     * @param bool $is_temp
     * @return null|string
     */
    public function save($media_id, $file_name = null, $is_temp = true)
    {
        $tmp_img_file_name = $file_name ?: md5($media_id);

        try {
            if ($is_temp) {
                $this->saveTempMaterial($media_id, storage_path($tmp_img_file_name));
            } else {
                $this->savePermanentMaterial($media_id, storage_path($tmp_img_file_name));
            }
        } catch (\Exception $e) {
            return null;
        }

        return storage_path($tmp_img_file_name);
    }

    /**
     * 保存临时素材
     *
     * @param $temp_media_id
     * @param $local_path_name
     */
    public function saveTempMaterial($temp_media_id, $local_path_name)
    {
        $resource = $this->wx_app->media->get($temp_media_id);
        file_put_contents($local_path_name, $resource);
    }

    /**
     * 保存永久素材
     *
     * @param $media_id
     * @param $local_path_name
     */
    public function savePermanentMaterial($media_id, $local_path_name)
    {
        $resource = $this->wx_app->media->get($media_id);
        file_put_contents($local_path_name, $resource);
    }


    /**
     * 上传临时图片 并返回 media id
     * @param $upload_img_path
     * @return Collection
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function uploadTempImage($upload_img_path)
    {

        $wx_temp = $this->wx_app->media;
//        $wx_temp = (new AppFactory())->authorizerApp($appid)->material;

        /** @var Collection $material */

        $material = $wx_temp->uploadImage($upload_img_path);

        return $material;
    }


    /**
     * 上传临时视频 并返回 media id
     *
     * @param $upload_img_path
     * @return Collection
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function uploadTempVideo($upload_img_path)
    {
        $wx_temp = $this->wx_app->media;

        /** @var Collection $material */
//  example [
//    "type" => "video"
//    "media_id" => "qogCZ-qLJrjD0Aqo1-0TfZRr4QYOxMZPWG_N2DO1XYkuD-NUVJgGmEgEK_vwgKjU"
//    "created_at" => 1516615206
//  ]
        $material = $wx_temp->uploadVideo($upload_img_path);

        return $material;
    }
}
